﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace Gladkikh.Sims2.Combiner.Controls
{
    using Database;

    public partial class AddonsFlowPanel : UserControl
    {
        public AddonsFlowPanel()
        {
            InitializeComponent();
            addonControls = new List<AddonControl>();
        }

        bool autoSave;

        [DisplayName("Автосейв")]
        [Category("Сим2ФлоуПанель")]
        [Description("Будет ли панель автосейвиться")]
        public bool AutoSave
        {
            get { return autoSave; }
            set { autoSave = value; }
        }


        List<Sims2Addon> addons;
        public List<Sims2Addon> Addons
        {
            get { return addons; }
            set
            {
                addons = value;
                ReBuildFlow();
            }
        }

        List<AddonControl> addonControls;

        public void ReBuildFlow()
        {
            SuspendLayout();
            tableLayoutPanel1.SuspendLayout();


            if (addons != null)
            {
                addonControls = new List<AddonControl>();

                tableLayoutPanel1.RowCount = 1;
                tableLayoutPanel1.Controls.Clear();

                foreach (Sims2Addon add in addons)
                {
                    AddonControl ac = new AddonControl(add);
                    ac.Dock = DockStyle.Fill;
                    ac.MaximumSize = new Size(0, 26);
                    addonControls.Add(ac);
                    tableLayoutPanel1.Controls.Add(ac);
                    tableLayoutPanel1.RowCount++;
                }
            }

            foreach (AddonControl ac in addonControls)
                ac.SetSize(Size.Width - 10);

            AllignColumns();

            ResumeLayout(false);
            tableLayoutPanel1.ResumeLayout(false);
        }

        private void AddonsFlowPanel_Resize(object sender, EventArgs e)
        {
            SuspendLayout();
            //   foreach (AddonControl ac in addonControls)
            //     ac.SetSize(Size.Width - 10);
            // AllignColumns();
            ResumeLayout(false);
        }

        bool Search_isGameDir(string[] dirs)
        {
            int i = 0;

            foreach (string dir in dirs)
                if (Path.GetFileName(dir) == "TSBin" || Path.GetFileName(dir) == "TSData" || Path.GetFileName(dir) == "CSBin")
                    i++;

            if (i == 3)
                return true;

            return false;
        }

        private void SearchDir(string path)
        {
            SearchDir(path, 4);
        }

        bool InSearch;

        public event EventHandler OnSearchBegin;

        private bool inSearch
        {
            get 
            { 
                return InSearch; 
            }
            set 
            { 
                InSearch = value;
                if (value)
                {
                    if (OnSearchBegin != null)
                        OnSearchBegin(this, new EventArgs());
                }
                else
                {
                    if (OnSearchComplete != null)
                        OnSearchComplete(this, new EventArgs());
                }
            }
        }


        private void SearchDir(string path, int level)
        {
            if (inSearch)
            {
                ww.SetText(path);
                ww.AddWait();
                if (level % 3 == 0)
                    Application.DoEvents();
                if (level > 0)
                {
                    try
                    {
                        string[] dirs = Directory.GetDirectories(path);

                        if (Search_isGameDir(dirs))
                        {
                            string[] files = Directory.GetFiles(path + "\\TSBin", "Sims2*.exe");

                            if (files.Length > 0)
                            {
                                SearchFinded(files[0]);
                            }
                        }
                        else
                            foreach (string dir in dirs)
                            {
                                SearchDir(dir, level - 1);
                            }
                    }
                    catch (UnauthorizedAccessException e)
                    {
                        ww.SetText(e.Message);
                        Application.DoEvents();
                    }
                    catch 
                    {

                    }
                }
            }
        }
        ///


        /// <summary>
        /// Поиск в папке на указанную глубину 
        /// </summary>
        /// <param name="path">Где искать</param>
        /// <param name="level">На какой максимально уровень производить поиск</param>
        public void SearchForAddon(string path, int level)
        {
            if (inSearch == false)
            {
                ShowWaitWindow();
                inSearch = true;
                SearchDir(path, level);
                HideWaitWindow();
            }

        }

        /// <summary>
        /// Автопоиск в папке на уовень выше ехешника
        /// </summary>
        public void SearchIt()
        {
            SearchForAddon(Path.GetDirectoryName(Path.GetDirectoryName(Application.ExecutablePath)), 4);
            //SearchDir(@"E:\Elected\Game\The Sims 2\");
            UpdateAddonControls();
        }

        WaitWindow ww;

        private void ShowWaitWindow()
        {
            if (ww == null)
                ww = new WaitWindow();

            ww.Reset();

            ww.OnButtonCancelClick += new EventHandler(ww_OnButtonCancelClick);
            ww.Show();
        }

        void ww_OnButtonCancelClick(object sender, EventArgs e)
        {
            inSearch = false;
            HideWaitWindow();
        }

        private void HideWaitWindow()
        {
            inSearch = false;
           if(ww != null) ww.Hide();
            ww = null;
        }

        private void SearchFinded(string filename)
        {
            int i = 0;

            foreach (AddonControl ac in addonControls)
            {
                if (Path.GetFileName(filename).ToUpper() == ac.Addon.Exe.ToUpper())
                {
                    Sims2Addon ad = ac.Addon;
                    ad.ExePath = filename;
                    ac.Addon = ad;
                }

                if (ac.Addon.ExePath == "" || ac.Addon.ExePath == null)
                    if (!File.Exists(ac.Addon.ExePath))
                        i++;
            }

            if (i == 0)
                HideWaitWindow();
        }

        public void ClearExePaths()
        {
            foreach (AddonControl ac in addonControls)
                ac.Addon.SetExePath("");
        }

        private void UpdateAddonControls()
        {
            foreach (AddonControl ac in addonControls)
                ac.UpdateIt();
        }

        public void BuildRegistry()
        {
            Sims2RegBuilder.Build(addons);
        }

        public void AllignColumns()
        {
            int maxsize = 0;

            foreach (AddonControl ac in addonControls)
                if (maxsize < ac.CheckBoxSize)
                    maxsize = ac.CheckBoxSize;

            foreach (AddonControl ac in addonControls)
                ac.SetCheckBoxSize(maxsize);
        }

        public int RecommendedHeight
        {
            get
            {
                return addonControls[addonControls.Count - 1].Bottom + 5;
            }
        }

        /// <summary>
        /// Событие выполняется когда закончен поиск.
        /// </summary>
        public event EventHandler OnSearchComplete;
    }
}
